const child_process = require("child_process");
const chalk = require("chalk");
const projectList = require("../project.json");
const inquirer = require("inquirer");

/**
 * 检查项目是否存在
 * @param {*} name 项目名称
 */
function checkProject(name) {
    if (!projectList[name]) {
        console.log(chalk.red(`项目"${name}"不存在，请检查之后重试。`));
        process.exit(1);
    }
}
/**
 * 检查文件夹名称
 * @param {*} folderName 文件夹名称
 */
function checkFolder(folderName) {
    if (!folderName) {
        console.log(chalk.red(`请输入文件夹名称`));
        process.exit(1);
    }
}
/**
 * 获取下载的分支
 * @param {*} folderName 文件夹名称
 * @param {*} projectName 项目名称
 * @param {*} branch 分支
 * @param {*} auth 作者
 */
function getUrl(folderName, projectName, branch, auth) {
    const args = [];
    if (branch) {
        args.push("-b " + branch);
    }
    args.push("--depth 1");
    args.push(folderName);
    return `git clone https://github.com/${auth}/${projectName}.git  ${args.join(" ")}`;
}

/**
 * 下载文件到本地
 * @param {*} folderName 文件夹名称
 * @param {*} name 项目名
 * @param {*} branch 分支
 */
function init(folderName, name, branch) {
    //2执行
    const data = projectList[name];
    const url = getUrl(folderName, name, branch || data.branch, data.auth);
    const pwd = process.cwd();
    console.log(chalk.green("当前目录", pwd));
    child_process.execSync(url);
    console.log(chalk.green("模版安装成功"));
    child_process.execSync(`rm -rf ${folderName}/.git`);
}

module.exports = function (program) {
    program
        .command("init folderName [name,branch]")
        .description("初始化项目，输入类型来创建目录")
        .action(function (source, target) {
            console.log("输出内容");
            const list = [];
            for (const key in projectList) {
                list.push(key);
            }
            inquirer
                .prompt([
                    {
                        type: "list",
                        message: "请选择要安装的模版:",
                        name: "name",
                        choices: list,
                    },
                    {
                        type: "input",
                        message: "请选择要安装的分支:",
                        name: "branch",
                        default: "master",
                    },
                ])
                .then((res) => {
                    const args = target.args;
                    const folderName = args[0];
                    checkFolder(folderName);
                    checkProject(res.name);
                    console.log(chalk.green("即将安装", res.name, "分支", res.branch));
                    init(folderName, res.name, res.branch);
                });
        });
};
